package com.rupertjones.globalcron.domain.dao;

import com.rupertjones.globalcron.domain.BaseEntity;
import org.hibernate.event.PostDeleteEvent;
import org.hibernate.event.PostInsertEvent;
import org.hibernate.event.PostUpdateEvent;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>&copy Rupert Jones 2012</p>
 *
 * @author rup
 */
public class SelectingPostPersistenceEventListener implements PostPersistenceEventListener {

    private List<PostPersistenceEventListener> listeners = new ArrayList<PostPersistenceEventListener>();

    public SelectingPostPersistenceEventListener(List<PostPersistenceEventListener> listeners) {
        this.listeners = listeners;
    }

    @Override
    public void setSessionContextProvider(SessionContextProvider provider) {
        for (PostPersistenceEventListener listener : listeners) {
            listener.setSessionContextProvider(provider);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onPostDelete(PostDeleteEvent event) {
        for (PostPersistenceEventListener listener : get((Class<? extends BaseEntity>) event.getEntity().getClass())) {
            listener.onPostDelete(event);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onPostInsert(PostInsertEvent event) {
        for (PostPersistenceEventListener listener : get((Class<? extends BaseEntity>) event.getEntity().getClass())) {
            listener.onPostInsert(event);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onPostUpdate(PostUpdateEvent event) {
        for (PostPersistenceEventListener listener : get((Class<? extends BaseEntity>) event.getEntity().getClass())) {
            listener.onPostUpdate(event);
        }
    }

    @Override
    public boolean supports(Class<? extends BaseEntity> clazz) {
        return true;
    }

    private List<PostPersistenceEventListener> get(Class<? extends BaseEntity> clazz) {
        List<PostPersistenceEventListener> selectedListeners = new ArrayList<PostPersistenceEventListener>();
        for (PostPersistenceEventListener listener : listeners) {
            if (listener.supports(clazz)) {
                selectedListeners.add(listener);
            }
        }
        return selectedListeners;
    }
}
